import os, time, sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

import socket
import selectors


class selectFtpClient:
    def __init__(self):

        self.port = ("127.0.0.1", 8001)
        self.create_socket()
        self.command_fanout()

    def create_socket(self):
        try:
            self.sock = socket.socket()
            self.sock.connect(self.port)
            print("连接FTP成功!")
        except Exception:
            print("连接失败!")

    def command_fanout(self):
        while True:
            cmd = input(">>>").strip()
            if cmd == "exit()":
                break
            cmd, file = cmd.split()
            if hasattr(self, cmd):
                func = getattr(self, cmd)
                func(cmd, file)
            else:
                print('调用错误！')

    # 上传
    def put(self, cmd, file):
        if os.path.isfile(file):
            fileName = os.path.basename(file)
            fileSize = os.path.getsize(file)
            fileInfo = "%s|%s|%s" % (cmd, fileName, fileSize)
            self.sock.send(bytes(fileInfo, encoding="utf-8"))
            recvStatus = self.sock.recv(1024)
            hasSend = 0
            if str(recvStatus, encoding="utf-8") == 'ok':
                with open(file, "rb") as f:
                    while fileSize > hasSend:
                        contant = f.read(10)
                        recv_size = len(contant)
                        self.sock.send(contant)
                        hasSend += recv_size
                        s = str(int(hasSend / fileSize * 100)) + "%"
                        print("正在上传文件：" + fileName + "   已经上传：  " + s)
                        time.sleep(0.5)
                print("%s文件上传完毕" % (fileName,))
            else:
                print("文件不存在")

    # 下载
    def get(self, cmd, file):

        fileInfo = "%s|%s" % (cmd, file)
        self.sock.send(bytes(fileInfo, encoding="utf-8"))
        filesize = int(self.sock.recv(10).decode("utf-8"))

        f = open(file, "ab")
        i = 0
        while i < filesize:
            self.sock.send("ok".encode("utf-8"))
            data = self.sock.recv(10)
            f.write(data)
            i += len(data)
            s = str(int(i / filesize * 100)) + "%"
            print("正在上传文件：" + file + "   已经下载：  " + s)

        print("下载完成")
        f.close()


if __name__ == "__main__":
    selectFtpClient()